package com.panda.web.service.py.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.panda.common.core.domain.model.LoginUser;
import com.panda.common.utils.SecurityUtils;
import com.panda.common.utils.StringUtils;
import com.panda.web.domain.JobCondition;
import com.panda.web.domain.dto.JobDTO;
import com.panda.web.domain.vo.CompanyVO;
import com.panda.web.domain.vo.JobVO;
import com.panda.web.domain.vo.UserVO;
import com.panda.web.domain.vo.commons.CompanyJobVO;
import com.panda.web.entity.commons.SearchContent;
import com.panda.web.entity.py.Company;
import com.panda.web.entity.py.Job;
import com.panda.web.entity.py.JobComplaint;
import com.panda.web.entity.wechat.WechatUser;
import com.panda.web.entity.wechatinfo.*;
import com.panda.web.mapper.commons.PushJobMapper;
import com.panda.web.mapper.commons.SearchContentMapper;
import com.panda.web.mapper.product.OpenidProductMapper;
import com.panda.web.mapper.py.CompanyMapper;
import com.panda.web.mapper.py.JobComplaintMapper;
import com.panda.web.mapper.py.JobMapper;
import com.panda.web.mapper.wechat.WechatUserMapper;
import com.panda.web.mapper.wechatinfo.*;
import com.panda.web.service.py.IJobService;
import org.apache.ibatis.annotations.Param;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
import com.panda.web.utils.pageutils.PageResult;
import org.springframework.transaction.annotation.Transactional;


/**
 * 职位Service业务层处理
 *
 * @author cpanda
 * @date 2025-03-03
 */
@Slf4j
@Service
public class JobServiceImpl extends ServiceImpl<JobMapper, Job> implements IJobService {
    @Autowired
    JobMapper jobMapper;
    @Autowired
    CompanyMapper companyMapper;
    @Autowired
    WechatUserinfoMapper userinfoMapper;
    @Autowired
    UserScientificResearchMapper researchMapper;
    @Autowired
    UserSchoolgoMapper schoolgoMapper;
    @Autowired
    UserProjectMapper projectMapper;
    @Autowired
    UserSkillMapper skillMapper;//技能证书
    @Autowired
    UserHonorMapper honorMapper;//荣誉

    @Autowired
    SearchContentMapper contentMapper;
    @Autowired
    UserDemandMapper demandMapper;
    @Autowired
    OpenidProductMapper openidProductMapper;
    @Autowired
    WechatUserMapper userMapper;
    @Autowired
    PushJobMapper pushJobMapper;
    @Autowired
    UserMajorRgppMapper userMajorRgppMapper;
    @Autowired
    EnshrineJobMapper enshrineJobMapper;
    @Autowired
    ProgressJobMapper progressJobMapper;
    @Autowired
    private JobComplaintMapper complaintMapper;

    /**
     * 分页查询
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<JobVO> PageList(JobDTO dto, Integer pageNum, Integer pageSize) throws JsonProcessingException, ParseException {

        Page<Job> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Job> queryWrapper = new QueryWrapper();//需要处理查询条件
        IPage<Job> jobIPage = jobMapper.selectPage(page, queryWrapper);
        long total = jobIPage.getTotal();
        List<Job> records = jobIPage.getRecords();
        List<JobVO> voList = jobVoToList(records);//封装vo数据方法

        return new PageResult<>(voList, total, pageNum, pageSize);
    }


    /**
     * 无分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public List<JobVO> choiceList(JobDTO dto) throws JsonProcessingException, ParseException {
        QueryWrapper<Job> queryWrapper = new QueryWrapper();//需要处理查询条件
        //构建查询条件
        queryWrapper.ne("company_id", "-");
        List<Job> jobList = jobMapper.selectList(queryWrapper);
        List<JobVO> voList = jobVoToList(jobList);//封装vo数据方法
        return voList;
    }

    @Override
    public JobVO selectByHQYId(JobDTO dto) throws ParseException {
        JobVO vo = new JobVO();
        Long jobId = dto.getId();
        String openid = dto.getOpenid();
        Job job = jobMapper.selectById(jobId);
        BeanUtils.copyProperties(job, vo);
        if (Objects.equals(job.getEndTime(), "0")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = vo.getStartTime();
            if (!Objects.equals(startTime, "0")) {
                Date startDate = sdf.parse(startTime);
                // 使用 Calendar 类来加上 3 个月
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                calendar.add(Calendar.MONTH, 3); // 加 3 个月
                // 将新的时间格式化为字符串
                String newEndTime = sdf.format(calendar.getTime());
                vo.setEndTime(newEndTime);
            } else {
                vo.setEndTime("未设置时间");
            }

        }
        String crawlingPlatform = job.getCrawlingPlatform();
//        if (Objects.equals(crawlingPlatform, "23465")) {
//            vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
//        } else {
//            vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
//        }
        if (Objects.equals(crawlingPlatform, "") || Objects.equals(crawlingPlatform, null)) {
            vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
        } else if (Objects.equals(crawlingPlatform, "菜鸟")) {
            vo.setWebsite(vo.getSource());
        } else {
            vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
        }
        String companyId = job.getCompanyId();
        List<Company> companyList = companyMapper.findByCompanyId(companyId);
        String districtList = job.getDistrictList();
        // 创建 Gson 对象
        Gson gson = new Gson();
        String areaCn = null;
        if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
            String areaChList = getAreaCnList(districtList);
            vo.setAreaCn(areaChList);
        } else {
            if (companyList.size() > 0) {// 如果 districtList 为 null，使用 companyList
                areaCn = companyList.get(0).getAreaCn();
            }
            vo.setAreaCn(areaCn);
        }
        if (companyList.size() > 0) {
            vo.setIndustryCn(companyList.get(0).getIndustryCn());
            vo.setComId(companyList.get(0).getCompanyId());
            vo.setName(companyList.get(0).getName());
            vo.setComNatureCn(companyList.get(0).getNatureCn());
            vo.setShowLogo(companyList.get(0).getShowLogo());
        }
        String startTime = formatDate(vo.getStartTime());
        String endTime = formatDate(vo.getEndTime());
        vo.setStartTime(startTime);
        vo.setEndTime(endTime);
//        vo.setWebsite(companyList.get(0).getWebsite());
        if (!Objects.equals(vo.getMajorCn(), null)) {
            String majorCn = vo.getMajorCn().trim(); // 去除前后空格
            if (!majorCn.isEmpty()) {
                // 按逗号分隔，并过滤掉空字符串
                List<String> list = Arrays.stream(majorCn.split(","))
                        .map(String::trim) // 去除每个元素的前后空格
                        .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                        .collect(Collectors.toList());
                vo.setMajorList(list);
            } else {
                vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
            }
        } else {
            vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
        }


        if (!Objects.equals(openid, null)) {
            WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
            if (userinfo != null) {
                List<UserDemand> demandList = demandMapper.findByOpenid(openid);
                List<String> conditionList = new ArrayList<>();
                Integer degree = 50;
                degree = getInteger(userinfo, conditionList, degree, areaCn, demandList, openid);
                vo.setDegree(degree);
                vo.setConditionList(conditionList);
            }
            int count = enshrineJobMapper.findByOpenidAndJobId(openid, jobId);
            if (count > 0) {
                vo.setEnshrineStatus("1");
            } else {
                vo.setEnshrineStatus("0");
            }
            ProgressJob progressJob = progressJobMapper.findByOpenidAndJobId(openid, jobId);
            if (progressJob != null) {
                String progressType = progressJob.getProgressType();
                vo.setProgressType(progressType);
            } else {
                vo.setProgressType("0");
            }
        } else {
            vo.setEnshrineStatus("0");
            vo.setProgressType("0");
        }
        return vo;
    }

    /**
     * 新增投诉
     *
     * @param complaint
     * @return
     */
    @Transactional
    @Override
    public int insert(JobComplaint complaint) {
        Long jobId = complaint.getJobId();
        Job job = jobMapper.selectById(jobId);
        if (!Objects.equals(job.getJobName(), null)) {
            complaint.setJobName(job.getJobName());
        }
        if (!Objects.equals(job.getCompanyName(), null)) {
            complaint.setCompanyName(job.getCompanyName());
        }
        complaint.setCreationTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        complaintMapper.insert(complaint);
        return 1;
    }

    /**
     * 投诉列表
     *
     * @param complaint
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<JobComplaint> selectByJobComplaint(JobComplaint complaint, Integer pageNum, Integer pageSize) {

        Page<JobComplaint> page = new Page<>(pageNum, pageSize);
        QueryWrapper<JobComplaint> queryWrapper = new QueryWrapper();//需要处理查询条件
        if (complaint.getJobName() != null) {
            queryWrapper.like("job_name", complaint.getJobName());
        }
        if (complaint.getCompanyName() != null) {
            queryWrapper.like("company_name", complaint.getCompanyName());
        }
        queryWrapper.orderByDesc("creation_time");
        IPage<JobComplaint> userIPage = complaintMapper.selectPage(page, queryWrapper);
        long total = userIPage.getTotal();
        List<JobComplaint> records = userIPage.getRecords();

        return new PageResult<>(records, total, pageNum, pageSize);
    }


    /**
     * 查询岗位列表
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<JobVO> getJobList(JobDTO dto, Integer pageNum, Integer pageSize) throws JsonProcessingException, ParseException {
        Page<Job> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Job> queryWrapper = new QueryWrapper();//需要处理查询条件
        getQueryWrapperJob(dto, queryWrapper);//查询条件

        // 地址查询
        if (dto.getAdders() != null && !dto.getAdders().isEmpty()) {
            List<String> stringList = removeCitySuffix(dto.getAdders());
            queryWrapper.and(wrapper -> stringList.forEach(adder -> wrapper.or().like("district_list", adder)));
        }
        //是否匹配党员politicsStatus
        if (!Objects.equals(dto.getPoliticsStatus(), null) && Objects.equals(dto.getPoliticsStatus(), "1")) {
            queryWrapper.notLike("contents", "党员").notLike("job_name", "党员");
        }

        // 岗位类型

        if (dto.getNaturecnList() != null && !dto.getNaturecnList().isEmpty()) {
            System.out.println(dto.getNaturecnList());
            queryWrapper.and(wrapper -> dto.getNaturecnList().forEach(natureCn -> wrapper.or().like("nature_cn", natureCn)));
        }
        // 企业类型
        if (dto.getNaturecnConList() != null && !dto.getNaturecnConList().isEmpty()) {
            queryWrapper.and(wrapper -> dto.getNaturecnConList().forEach(c -> wrapper.or().like("company_info", c)));
        }
        IPage<Job> userIPage = jobMapper.selectPage(page, queryWrapper);
        long total = userIPage.getTotal();
        List<Job> records = userIPage.getRecords();
        List<JobVO> voList = jobVoToList(records);//封装vo数据方法
        return new PageResult<>(voList, total, pageNum, pageSize);
    }



    //岗位列表查询条件
    private void getQueryWrapperJob(JobDTO dto, QueryWrapper<Job> queryWrapper) {
        queryWrapper.ne("company_id", '-');



        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }
        if (dto.getZygwqi() != null) {
            queryWrapper.like("job_name", dto.getZygwqi()).or().like("company_name", dto.getZygwqi()).or().like("company_info", dto.getZygwqi());
        }

        if (dto.getJobName() != null) {
            queryWrapper.like("job_name", dto.getJobName());
        }

        if (dto.getCompanyName() != null) {
            queryWrapper.like("company_name", dto.getCompanyName());
        }

        if (dto.getContents() != null) {
            queryWrapper.like("contents", dto.getContents());
        }

        // 学历查询（确保非空）
        if (dto.getEducationcn() != null) {
            List<String> stringList = getBacjground(dto.getEducationcn());
            if (!stringList.isEmpty()) {
                queryWrapper.and(wrapper -> stringList.forEach(edu -> wrapper.or().like("education_cn", edu)));
            }
        }


        // 专业查询
        if (dto.getMajorcnList() != null && !dto.getMajorcnList().isEmpty()) {
            List<String> processedMajors;

            if (Objects.equals(dto.getEducationcn(), "本科") || Objects.equals(dto.getEducationcn(), "大专")) {
                // 本科和大专：检查数组中是否包含一级学科
                boolean containsUndergraduate = dto.getMajorcnList().stream()
                        .anyMatch(major -> major != null && containsUndergraduateDiscipline(major));

                if (containsUndergraduate) {
                    // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                    processedMajors = dto.getMajorcnList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                } else {
                    // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                    processedMajors = dto.getMajorcnList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                            .skip(1) // 跳过第一个
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                }
            } else {
                // 硕士：检查数组中是否包含一级学科
                boolean containsGraduate = dto.getMajorcnList().stream()
                        .anyMatch(major -> major != null && containsGraduateDiscipline(major));

                if (containsGraduate) {
                    // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                    processedMajors = dto.getMajorcnList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                } else {
                    // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                    processedMajors = dto.getMajorcnList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                            .skip(1)
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());

                }
            }

            // 使用处理后的专业列表进行查询
            if (!processedMajors.isEmpty()) {
                final List<String> finalProcessedMajors = processedMajors;
                queryWrapper.and(wrapper -> finalProcessedMajors.forEach(major ->
                        wrapper.or().like("major_cn", major)
                ));
            }
            if (Objects.equals(dto.getBxzy(), "1")) {
                queryWrapper.and(wrapper ->
                        wrapper.like("contents", "专业不限")
                                .or()
                                .like("major_cn", "不限")
                );
            }




        }

        // 专业或内容查询（确保非空）
        if (dto.getMajorContentsList() != null && !dto.getMajorContentsList().isEmpty()) {

            List<String> processedMajors;

            if (Objects.equals(dto.getEducationcn(), "本科") || Objects.equals(dto.getEducationcn(), "大专")) {
                // 本科和大专：检查数组中是否包含一级学科
                boolean containsUndergraduate = dto.getMajorContentsList().stream()
                        .anyMatch(major -> major != null && containsUndergraduateDiscipline(major));

                if (containsUndergraduate) {
                    // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                    processedMajors = dto.getMajorContentsList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                } else {
                    // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                    processedMajors = dto.getMajorContentsList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                            .skip(1) // 跳过第一个
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                }
            } else {
                // 硕士：检查数组中是否包含一级学科
                boolean containsGraduate = dto.getMajorContentsList().stream()
                        .anyMatch(major -> major != null && containsGraduateDiscipline(major));

                if (containsGraduate) {
                    // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                    processedMajors = dto.getMajorContentsList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                } else {
                    // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                    processedMajors = dto.getMajorContentsList().stream()
                            .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                            .skip(1) // 跳过第一个
//                            .map(major -> removeClassSuffix(major.trim()))
                            .distinct()
                            .collect(Collectors.toList());
                }
            }

            // 使用处理后的专业列表进行查询
            if (!processedMajors.isEmpty()) {
                final List<String> finalProcessedMajors = processedMajors;
                queryWrapper.and(wrapper -> finalProcessedMajors.forEach(major ->
                        wrapper.or().like("major_cn", major).or().like("contents", major)
                ));
            }
        }

        // 企业类型查询
        if (dto.getQylx() != null && !dto.getQylx().isEmpty()) {
            queryWrapper.and(wrapper -> dto.getQylx().forEach(qylx -> wrapper.or().like("company_info", qylx)));
        }
        queryWrapper.notLike("crawling_platform", "大学");
        queryWrapper.orderByDesc("start_time");
    }

    /**
     * 前台人岗匹配自主筛选
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Transactional

    @Override
    public synchronized PageResult<JobVO> getQTJobList(JobDTO dto, Integer pageNum, Integer pageSize) throws ParseException, JsonProcessingException {
        Page<Job> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Job> queryWrapper = new QueryWrapper();//需要处理查询条件
        queryWrapper.ne("company_id", '-');

        // 地址查询
        if (dto.getSsdizhi() != null && !dto.getSsdizhi().isEmpty()) {
            dto.setAdders(splitToList(dto.getSsdizhi()));
            List<String> stringList = removeCitySuffix(dto.getAdders());
            queryWrapper.and(wrapper -> stringList.forEach(a -> wrapper.or().like("district_list", a)));
        }
        //是否匹配党员politicsStatus
        if (!Objects.equals(dto.getPoliticsStatus(), null) && Objects.equals(dto.getPoliticsStatus(), "1")) {
            queryWrapper.notLike("contents", "党员").notLike("job_name", "党员");
        }
        // 企业类型
        if (dto.getSsqylx() != null && !dto.getSsqylx().trim().isEmpty()) {
            dto.setNaturecnConList(splitToList(dto.getSsqylx()));
            queryWrapper.and(wrapper -> dto.getNaturecnConList().forEach(c -> wrapper.or().like("company_info", c)));
        }
        // 岗位类型
        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
            dto.setNaturecnList(splitToList(dto.getSsgwlx()));
            queryWrapper.and(wrapper -> dto.getNaturecnList().forEach(natureCn -> wrapper.or().like("nature_cn", natureCn)));
        }

        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
            dto.setEducationcnList(splitToList(dto.getSsxllx()));
        }

        if (dto.getId() != null) {
            queryWrapper.eq("id", dto.getId());
        }
        if (dto.getZygwqi() != null) {
            queryWrapper.like("job_name", dto.getZygwqi()).or().like("company_name", dto.getZygwqi()).or().like("company_info", dto.getZygwqi());
        }

        if (dto.getJobName() != null) {
            queryWrapper.like("job_name", dto.getJobName());
        }

        if (dto.getCompanyName() != null) {
            queryWrapper.like("company_name", dto.getCompanyName());
        }

        if (dto.getContents() != null) {
            queryWrapper.like("contents", dto.getContents());
        }

        // 学历查询（确保非空）
        if (dto.getEducationcn() != null) {
            List<String> stringList = getBacjground(dto.getEducationcn());
            if (!stringList.isEmpty()) {
                queryWrapper.and(wrapper -> stringList.forEach(edu -> wrapper.or().like("education_cn", edu)));
            }
        }
        if (Objects.equals(dto.getBxzy(), "1")) {
            queryWrapper.and(wrapper ->
                    wrapper.like("major_cn", "不限").or().like("contents", "专业不限")
            );
        }
        // 专业查询
        if (dto.getSszhuanye() != null) {
            dto.setMajorcnList(splitToList(dto.getSszhuanye()));
            List<String> processedMajors;
            if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
                dto.setEducationcn(dto.getSsxllx());
                System.out.println("学历    ：" + dto.getEducationcn());
                System.out.println("专业    ：" + dto.getMajorcnList());
                if (Objects.equals(dto.getEducationcn(), "本科") || Objects.equals(dto.getEducationcn(), "大专")) {
                    // 本科和大专：检查数组中是否包含一级学科
                    boolean containsUndergraduate = dto.getMajorcnList().stream()
                            .anyMatch(major -> major != null && containsUndergraduateDiscipline(major));

                    if (containsUndergraduate) {
                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    } else {
                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .skip(1) // 跳过第一个
//                            .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    }
                } else {
                    // 硕士：检查数组中是否包含一级学科
                    boolean containsGraduate = dto.getMajorcnList().stream()
                            .anyMatch(major -> major != null && containsGraduateDiscipline(major));

                    if (containsGraduate) {
                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
//                            .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    } else {
                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .skip(1)
//                            .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());

                    }
                }

                // 使用处理后的专业列表进行查询
                if (!processedMajors.isEmpty()) {
                    System.out.println(processedMajors + "  1  111 1");
                    final List<String> finalProcessedMajors = processedMajors;
//                    queryWrapper.and(wrapper -> {
//                        for (String major : finalProcessedMajors) {
////                            wrapper.or().like("major_cn", major).or().like("contents", major);
//                        }
//                    });
                    queryWrapper.and(wrapper -> {
                        // 第一部分：遍历processedMajors的OR条件（对应foreach）
                        for (String item : finalProcessedMajors) {
                            wrapper.or(w -> w.like("b.major_cn", item)
                                    .or().like("b.om_cn", item)
                                    .or().like("b.contents", item)
                                    .or(w2 -> w2.isNull("b.major_cn").and(w3 -> w3.like("b.contents", item))));
                        }

                        // 第二部分："专业不限"的特定条件（OR关系）
                        wrapper.or(w -> w.like("b.contents", "专业不限")
                                .and(w2 -> w2.like("b.major_cn", "不限").or().isNull("b.major_cn")));
                    });
                }
            }

        }

        // 企业类型查询
        if (dto.getQylx() != null && !dto.getQylx().isEmpty()) {
            queryWrapper.and(wrapper -> dto.getQylx().forEach(qylx -> wrapper.or().like("company_info", qylx)));
        }
        queryWrapper.notLike("crawling_platform", "大学");
        queryWrapper.orderByDesc("update_time");
        IPage<Job> userIPage = jobMapper.selectPage(page, queryWrapper);
        long total = userIPage.getTotal();
        List<Job> records = userIPage.getRecords();
        List<JobVO> voList = jobVoToList(records);//封装vo数据方法

        if (dto.getOpenid() != null && dto.getPageNum() == 1 && (!Objects.equals(dto.getEducationcn(), null) || !Objects.equals(dto.getZygwqi(), null) || !Objects.equals(dto.getAdders(), null) || !Objects.equals(dto.getBxzy(), null))) {
            WechatUserinfo userinfo = userinfoMapper.findByOpenid(dto.getOpenid());
            Integer screenNumber = userinfo.getScreenNumber();
            if (screenNumber <= 0) {
                throw new RuntimeException("您的筛选次数已用完，请明天再试");
            } else {
                userinfo.setScreenNumber(screenNumber - 1);
                userinfoMapper.updateById(userinfo);
            }

        }
        return new PageResult<>(voList, total, pageNum, pageSize);

    }

    /**
     * 测试
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<JobVO> getQTJobAAList(JobDTO dto, Integer pageNum, Integer pageSize) throws ParseException, JsonProcessingException {
        Page<JobVO> page = new Page<>(pageNum, pageSize);
        // 地址查询
        if (dto.getSsdizhi() != null && !dto.getSsdizhi().isEmpty()) {
            dto.setAdders(splitToList(dto.getSsdizhi()));
            dto.setAdders(removeCitySuffix(dto.getAdders()));
        }

        // 企业类型
        if (dto.getSsqylx() != null && !dto.getSsqylx().trim().isEmpty()) {
            dto.setNaturecnConList(splitToList(dto.getSsqylx()));
        }
        // 岗位类型
        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
            dto.setNaturecnList(splitToList(dto.getSsgwlx()));
        }
        //学历
        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
            List<String> stringList = getBacjground(dto.getSsxllx());
            dto.setEducationcnList(stringList);
        }
        if (dto.getSszhuanye() != null) {
            dto.setMajorcnList(splitToList(dto.getSszhuanye()));
            List<String> processedMajors;
            if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
                dto.setEducationcn(dto.getSsxllx());
                System.out.println("学历    ：" + dto.getEducationcn());
                System.out.println("专业    ：" + dto.getMajorcnList());
                if (Objects.equals(dto.getEducationcn(), "本科") || Objects.equals(dto.getEducationcn(), "大专")) {
                    // 本科和大专：检查数组中是否包含一级学科
                    boolean containsUndergraduate = dto.getMajorcnList().stream()
                            .anyMatch(major -> major != null && containsUndergraduateDiscipline(major));

                    if (containsUndergraduate) {
                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    } else {
                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .skip(1) // 跳过第一个
                                .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    }
                } else {
                    // 硕士：检查数组中是否包含一级学科
                    boolean containsGraduate = dto.getMajorcnList().stream()
                            .anyMatch(major -> major != null && containsGraduateDiscipline(major));

                    if (containsGraduate) {
                        // 包含一级学科，直接返回去重数组，处理"-"和去掉"类"字
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());
                    } else {
                        // 不包含一级学科，去掉第一个（一级学科），只保留后面的
                        processedMajors = dto.getMajorcnList().stream()
                                .filter(major -> major != null && !major.trim().isEmpty() && !"-".equals(major.trim()))
                                .skip(1)
                                .map(major -> removeClassSuffix(major.trim()))
                                .distinct()
                                .collect(Collectors.toList());

                    }
                }

                // 使用处理后的专业列表进行查询
                if (!processedMajors.isEmpty()) {
                    System.out.println(processedMajors + "  1  111 1");
                    List<String> finalProcessedMajors = processedMajors;
                    dto.setMajList(finalProcessedMajors);
                }
            }

        }
        IPage<JobVO> houseIPage = jobMapper.selectJobPage(page, dto);

        List<JobVO> voList = jobVoToAAAList(houseIPage.getRecords());//封装vo数据方法
        if (dto.getOpenid() != null && dto.getPageNum() == 1 && (!Objects.equals(dto.getEducationcn(), null) || !Objects.equals(dto.getZygwqi(), null) || !Objects.equals(dto.getAdders(), null) || !Objects.equals(dto.getBxzy(), null))) {
            WechatUserinfo userinfo = userinfoMapper.findByOpenid(dto.getOpenid());
            Integer screenNumber = userinfo.getScreenNumber();
            if (screenNumber <= 0) {
                throw new RuntimeException("您的筛选次数已用完，请明天再试");
            } else {
                userinfo.setScreenNumber(screenNumber - 1);
                userinfoMapper.updateById(userinfo);
            }

        }

        return new PageResult<>(voList, houseIPage.getTotal(), pageNum, pageSize);
    }


    /**
     * 回显数据
     *
     * @param jobId
     * @return
     */
    @Override
    public JobVO selectById(Long jobId) throws ParseException {
        JobVO vo = new JobVO();
        Job job = jobMapper.selectById(jobId);
        BeanUtils.copyProperties(job, vo);

        String endTime = formatDate(vo.getEndTime());
        vo.setEndTime(endTime);
        if (Objects.equals(job.getEndTime(), "0")) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startTime = vo.getStartTime();
            if (!Objects.equals(startTime, "0")) {
                Date startDate = sdf.parse(startTime);
                // 使用 Calendar 类来加上 3 个月
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(startDate);
                calendar.add(Calendar.MONTH, 3); // 加 3 个月
                // 将新的时间格式化为字符串
                String newEndTime = sdf.format(calendar.getTime());
                vo.setEndTime(newEndTime);
            } else {
                vo.setEndTime("未设置时间");
            }

        }
        String startTime = formatDate(vo.getStartTime());
        vo.setStartTime(startTime);
        String crawlingPlatform = job.getCrawlingPlatform();
//        if (Objects.equals(crawlingPlatform, "23465")) {
//            vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
//        } else {
//            vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
//        }
        if (Objects.equals(crawlingPlatform, "") || Objects.equals(crawlingPlatform, null)) {
            vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
        } else if (Objects.equals(crawlingPlatform, "菜鸟")) {
            vo.setWebsite(vo.getSource());
        } else {
            vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
        }
        String companyId = job.getCompanyId();
        List<Company> companyList = companyMapper.findByCompanyId(companyId);
        String districtList = job.getDistrictList();
        // 创建 Gson 对象
        Gson gson = new Gson();
        String areaCn = null;
        if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
            String areaChList = getAreaCnList(districtList);
            vo.setAreaCn(areaChList);

        } else {
            if (companyList != null && !companyList.isEmpty()) {// 如果 districtList 为 null，使用 companyList
                areaCn = companyList.get(0).getAreaCn();
            }
            vo.setAreaCn(areaCn);
        }
        if (companyList != null && !companyList.isEmpty()) {
            vo.setIndustryCn(companyList.get(0).getIndustryCn());
            vo.setComId(companyList.get(0).getCompanyId());
            vo.setName(companyList.get(0).getName());
            vo.setComNatureCn(companyList.get(0).getNatureCn());
            vo.setShowLogo(companyList.get(0).getShowLogo());
        }

//        vo.setWebsite(companyList.get(0).getWebsite());
        if (!Objects.equals(vo.getMajorCn(), null)) {
            String majorCn = vo.getMajorCn().trim(); // 去除前后空格
            if (!majorCn.isEmpty()) {
                // 按逗号分隔，并过滤掉空字符串
                List<String> list = Arrays.stream(majorCn.split(","))
                        .map(String::trim) // 去除每个元素的前后空格
                        .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                        .collect(Collectors.toList());
                vo.setMajorList(list);
            } else {
                vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
            }
        } else {
            vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
        }
        String openid = SecurityUtils.getLoginUser().getOpenid();//当前用户openid;
        if (!Objects.equals(openid, null)) {
            WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
            if (userinfo != null) {
                List<UserDemand> demandList = demandMapper.findByOpenid(openid);
                List<String> conditionList = new ArrayList<>();
                Integer degree = 50;
                degree = getInteger(userinfo, conditionList, degree, areaCn, demandList, openid);
                vo.setDegree(degree);
                vo.setConditionList(conditionList);
            }
            int count = enshrineJobMapper.findByOpenidAndJobId(openid, jobId);
            if (count > 0) {
                vo.setEnshrineStatus("1");
            } else {
                vo.setEnshrineStatus("0");
            }
            ProgressJob progressJob = progressJobMapper.findByOpenidAndJobId(openid, jobId);
            if (progressJob != null) {
                String progressType = progressJob.getProgressType();
                vo.setProgressType(progressType);
            } else {
                vo.setProgressType("0");
            }

        } else {
            vo.setEnshrineStatus("0");
            vo.setProgressType("0");
        }
        return vo;
    }

    //返回分数

    private Integer getInteger(WechatUserinfo userinfo, List<String> conditionList, Integer degree, String areaCn, List<UserDemand> demandList, String openid) {
        if (Objects.equals(userinfo.getAge(), "男")) {
            conditionList.add("您的性别在央国企是占有优势的;");
            degree += 5;
        }

        if ("中共党员".equals(userinfo.getPolitics()) || "预备党员".equals(userinfo.getPolitics())) {
            conditionList.add("您的政治面貌已经超越了76.3%的求职者;");
            degree += 5;
        }
        if ("是".equals(userinfo.getEnglishSix())) {
            conditionList.add("您英语已过六级，超过了65.6%的求职者;");
            degree += 5;
        }

        if ("是".equals(userinfo.getComputerTwo())) {
            conditionList.add("您还有计算机二级，很难得，多数同学都没考的意识哦;");
            degree += 5;
        }
        //地点判断
        if (checkMatch(areaCn, demandList)) {
            degree += 5;
        }
        int researchCount = researchMapper.findByOpenidCount(openid);
        if (researchCount > 0) {
            conditionList.add("太棒了！91.5%的求职者都没有您的科研经历;");
            degree += 5;
        }
        int schoolCount = schoolgoMapper.findByOpenidCount(openid);
        if (schoolCount > 0) {
            conditionList.add("校园经历现虽不被央国企看重了，但您的质量较高哦;");
            degree += 5;
        }
        int projectCount = projectMapper.findByOpenidCount(openid);
        if (projectCount == 1) {
            conditionList.add("央国企非常看重实习或项目经历，您已经超越了61%的人;");
            degree += 5;
        } else if (projectCount >= 2) {
            conditionList.add("央国企非常看重实习或项目经历，您已经超越了61%的人;");
            degree += 10;
        }

        int honorCount = honorMapper.findByOpenidCount(openid);
        if (honorCount > 0) {
            conditionList.add("一看您就是优秀的人，获得了如此优秀的荣誉奖励，这是加分项哦;");
            degree += 5;
        }
        int skillCount = skillMapper.findByOpenidCount(openid);
        if (skillCount > 0) {
            conditionList.add("您与本专业相关的技能证书或资格证书是很多企业需要的！超过76%的应聘者啦;");
            degree += 5;
        }
        // 5. 毕业院校类别 普通本科+0分，211＋5分，985＋10分；
        if (!Objects.equals(userinfo.getGraduateType(), null) && Objects.equals(userinfo.getGraduateType(), "211") || Objects.equals(userinfo.getGraduateType(), "985")) {
            conditionList.add("您的学校，超过了86.5%的央国企求职者;");
        }
        if (!Objects.equals(userinfo.getGraduateType(), "211") || Objects.equals(userinfo.getGraduateType(), "985")) {
            degree += 5;
        }
        if (degree >= 100) {
            degree = 100;
        }
        return degree;
    }

    //判断地点是否符合
    public boolean isMatch(String areaCn, String target) {
        // 空值判断
        if (areaCn == null || target == null || areaCn.isEmpty() || target.isEmpty()) {
            return false;
        }

        // 将 areaCn 按 "-" 分割成不同的层级
        String[] areaLevels = areaCn.split("-");
        // 将 target 按 "," 分割成不同的地点
        String[] targets = target.split(",");
        // 遍历每个目标地点
        for (String t : targets) {
            // 去除空格
            t = t.trim();
            // 遍历 areaCn 的每个层级
            for (String level : areaLevels) {
                if (t.contains(level)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean checkMatch(String areaCn, List<UserDemand> demandList) {
        // 空值判断
        if (areaCn == null || demandList == null || demandList.isEmpty()) {
            return false;
        }

        // 获取相关字段
        String searchLocation = demandList.get(0).getSearchLocation(); // 意向地点
        String nativePlace = demandList.get(0).getNativePlace(); // 户籍地
        String graduateCity = demandList.get(0).getGraduateCity(); // 毕业院校

        // 只要有一个匹配就返回 true
        return isMatch(areaCn, searchLocation) || isMatch(areaCn, nativePlace) || isMatch(areaCn, graduateCity);
    }


    /**
     * 热门岗位推荐
     *
     * @return
     */
    @Override
    public PageResult<CompanyJobVO> getHot(JobDTO dto, Integer pageNum, Integer pageSize) {
        List<String> jobCompany = new ArrayList<>();
        jobCompany.addAll(Arrays.asList("中国移动", "中国联通", "中国石油", "中国联合", "国投", "华润", "研究院", "中国储备粮", "中国联合网络通信有限公司", "中国民航", "国家电投", "中国平安人寿"));
//        List<CompanyJobVO> voList = jobMapper.getHot();
        // 计算分页参数  （分页查询）
        int pageNumA = dto.getPageNum() == null ? 1 : dto.getPageNum(); // 默认第1页
        int pageSizeB = dto.getPageSize() == null ? 10 : dto.getPageSize(); // 默认每页10条
        int offset = (pageNumA - 1) * pageSizeB;
        dto.setPageNum(offset);
        dto.setPageSize(pageSize);
        dto.setJobCompany(jobCompany);
        Integer total = jobMapper.getTotalHot(dto);
        List<CompanyJobVO> voList = jobMapper.getHot(dto);
        for (CompanyJobVO vo : voList) {
            if (!Objects.equals(vo.getMajorCn(), null)) {
                String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                if (!majorCn.isEmpty()) {
                    // 按逗号分隔，并过滤掉空字符串
                    List<String> list = Arrays.stream(majorCn.split(","))
                            .map(String::trim) // 去除每个元素的前后空格
                            .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                            .collect(Collectors.toList());
                    vo.setMajorList(list);
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }
            } else {
                vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
            }
            String districtList = vo.getDistrictList();
            Gson gson = new Gson();
            if (districtList != null) {
                // 解析 JSON 字符串
                List<Map<String, Object>> districtListData = gson.fromJson(districtList, List.class);
                // 用来存储所有的 area_cn 字段
                StringBuilder areaCnBuilder = new StringBuilder();
                // 遍历所有数据项，获取每个 area_cn 的值
                for (Map<String, Object> district : districtListData) {
                    Object areaCnObject = district.get("area_cn");
                    if (areaCnObject instanceof String) {
                        // 添加到 StringBuilder
                        if (areaCnBuilder.length() > 0) {
                            areaCnBuilder.append("、"); // 使用中文逗号连接
                        }
                        areaCnBuilder.append(areaCnObject.toString());
                    }
                }
                // 获取合并后的 area_cn 字符串
                vo.setAreaCn(areaCnBuilder.toString());
            }
            String startTime = formatDate(vo.getStartTime());
            String endTime = formatDate(vo.getEndTime());
            vo.setStartTime(startTime);
            vo.setEndTime(endTime);
        }
        // 构建分页对象
        PageResult pageResult = new PageResult(voList, total, dto.getPageNum(), dto.getPageSize(), "ok", 200);
        return pageResult;
    }


    /**
     * 人岗匹配
     */
    @Override
    public PageResult<JobVO> selectByOpenid(JobDTO dto, Integer pageNum, Integer pageSize) throws ParseException {
        List<JobVO> voList = new ArrayList();
        String openid = dto.getOpenid();
        if (!StringUtils.isNotNull(openid)) {
            // 构建分页对象
            return getPageResult(voList);
        }
        WechatUser wechatUser = userMapper.findByOpenIdJOb(openid);
        List<Long> ids = openidProductMapper.findByOpenid(openid, "0");
        if (ids != null && !ids.isEmpty() || Objects.equals(wechatUser.getTrialStatus(), "1")) {
            Long max = 0l;
            if (ids.size() != 0) {
                max = Collections.max(ids);
            }
            if (max <= 1 && Objects.equals(wechatUser.getTrialStatus(), "1")) {
                return textPushJob(dto, pageSize, wechatUser, voList);//试用
            } else if (max >= 2) {
                return getPageResultJobList(dto, pageSize, openid, voList);//正常推送
            } else {
                return getPageResult(voList);
            }

        } else {
            return getPageResult(voList);
        }
    }


    //试用
    @NotNull
    private PageResult textPushJob(JobDTO dto, Integer pageSize, WechatUser wechatUser, List<JobVO> voList) throws ParseException {
        if (Objects.equals(wechatUser.getCepingStatus(), "1")) {
            List<Long> jobIds = pushJobMapper.findByOpenid(wechatUser.getOpenid());
            if (jobIds.size() == 0) {
                // 构建分页对象
                PageResult pageResult = new PageResult(voList, voList.size(), dto.getPageNum(), dto.getPageSize(), "ok", 200);
                return pageResult;
            } else {
                dto.setJobIds(jobIds);
                // 计算分页参数  （分页查询）
                int pageNumA = dto.getPageNum() == null ? 1 : dto.getPageNum(); // 默认第1页
                int pageSizeB = dto.getPageSize() == null ? 10 : dto.getPageSize(); // 默认每页10条
                int offset = (pageNumA - 1) * pageSizeB;
                dto.setPageNum(offset);
                dto.setPageSize(pageSize);

                // 确保 dto 和 dto.getAdders() 都不为 null
                List<String> newAdders = new ArrayList<>();
                if (dto != null && dto.getAdders() != null && !dto.getAdders().isEmpty()) {
                    for (String addr : dto.getAdders()) {
                        // 判断 addr 是否包含 "市"
                        if (addr.contains("市")) {
                            // 去掉 "市" 并添加到新集合
                            addr = addr.replace("市", "");
                        }
                        newAdders.add(addr);  // 添加处理后的地址
                    }
                    dto.setAdders(newAdders);
                }
                String background = wechatUser.getBackground();
                if (background != null) {
                    List<String> backgroundList = getBacjground(background);//学历
                    dto.setEducationcnList(backgroundList);
                }
                List<Job> jobIdList = jobMapper.findByComShiyong(dto);
                // 获取总记录数
                if (jobIdList != null && !jobIdList.isEmpty()) {
                    for (Job jobs : jobIdList) {
                        JobVO vo = new JobVO();
                        BeanUtils.copyProperties(jobs, vo);

                        if (!Objects.equals(vo.getMajorCn(), null)) {
                            String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                            if (!majorCn.isEmpty()) {
                                // 按逗号分隔，并过滤掉空字符串
                                List<String> list = Arrays.stream(majorCn.split(","))
                                        .map(String::trim) // 去除每个元素的前后空格
                                        .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                        .collect(Collectors.toList());
                                vo.setMajorList(list);
                            } else {
                                vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                            }
                        } else {
                            vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                        }
                        List<Company> company = companyMapper.findByCompanyIdById(jobs.getCompanyId());
                        String districtList = jobs.getDistrictList();
                        // 创建 Gson 对象
                        Gson gson = new Gson();
                        if (districtList != null) {
                            // 解析 JSON 字符串
                            List<Map<String, Object>> districtListData = gson.fromJson(districtList, List.class);
                            // 用来存储所有的 area_cn 字段
                            StringBuilder areaCnBuilder = new StringBuilder();
                            // 遍历所有数据项，获取每个 area_cn 的值
                            for (Map<String, Object> district : districtListData) {
                                Object areaCnObject = district.get("area_cn");
                                if (areaCnObject instanceof String) {
                                    // 添加到 StringBuilder
                                    if (areaCnBuilder.length() > 0) {
                                        areaCnBuilder.append("、"); // 使用中文逗号连接
                                    }
                                    areaCnBuilder.append(areaCnObject.toString());
                                }
                            }
                            // 获取合并后的 area_cn 字符串
                            String areaCn = areaCnBuilder.toString();
                            vo.setAreaCn(areaCn);
                        } else {
                            // 如果 districtList 为 null，使用 companyList
                            if (company != null && !company.isEmpty()) {
                                String areaCn = company.get(0).getAreaCn();
                                vo.setAreaCn(areaCn);
                            }
                        }
                        if (company != null && !company.isEmpty()) {
                            vo.setIndustryCn(company.get(0).getIndustryCn());
                            vo.setComId(company.get(0).getCompanyId());
                            vo.setName(company.get(0).getName());
                            vo.setComNatureCn(company.get(0).getNatureCn());
                        }
                        String startTime = formatDate(vo.getStartTime());
                        if (Objects.equals(vo.getEndTime(), "0")) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            Date startDate = sdf.parse(startTime);
                            // 使用 Calendar 类来加上 3 个月
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(startDate);
                            calendar.add(Calendar.MONTH, 3); // 加 3 个月
                            // 将新的时间格式化为字符串
                            String newEndTime = sdf.format(calendar.getTime());
                            vo.setEndTime(newEndTime);
                        } else {
                            String endTime = formatDate(vo.getEndTime());
                            vo.setEndTime(endTime);
                        }
                        vo.setStartTime(startTime);
                        voList.add(vo);
                    }
                }
                // 构建分页对象
                PageResult pageResult = new PageResult(voList, jobIdList.size(), dto.getPageNum(), dto.getPageSize(), "ok", 200);
                return pageResult;
            }

        } else {
            return getPageResult(voList);
        }
    }


    private PageResult getPageResultJobList(JobDTO dto, Integer pageSize, String openid, List<JobVO> voList) {
        WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
        if (userinfo == null) {
            // 构建分页对象
            return getPageResult(voList);
        }
        //添加搜索记录

        if (!Objects.equals(dto.getZygwqi(), null)) {
            SearchContent searchContent = new SearchContent();
            int count = contentMapper.findByOpenidAndContent(openid, dto.getZygwqi());
            if (count <= 0) {//不存在这个搜索记录,添加
                searchContent.setOpenid(openid);
                searchContent.setContent(dto.getZygwqi());
                contentMapper.insert(searchContent);
            }

        }

        //处理专业
        Set<String> uniqueMajors = new HashSet<>(); // 使用Set去重

        if (Objects.equals(userinfo.getBackground(), "本科") || Objects.equals(userinfo.getBackground(), "大专")) {
            // 本科和大专的专业处理
            List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(openid);
            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                    String majorName = majorRgpp.getMajorName();
                    if (majorName != null && !majorName.trim().isEmpty()) {
                        // 检查是否包含本科/大专的一级学科
                        if (containsUndergraduateDiscipline(majorName)) {
                            // 包含一级学科，需要拆分存储
                            String[] parts = majorName.split("-");
                            for (String part : parts) {
                                String trimmedPart = part.trim();
                                if (!trimmedPart.isEmpty()) {
                                    // 去掉"类"字，但保留"自动化类"
//                                    trimmedPart = removeClassSuffix(trimmedPart);
                                    uniqueMajors.add(trimmedPart);
                                }
                            }
                        } else {
                            // 不包含一级学科，只存储二级及以下
                            String[] parts = majorName.split("-");
                            if (parts.length > 1) {
                                // 有多个层级，去掉第一个（一级学科）
                                for (int i = 1; i < parts.length; i++) {
                                    String trimmedPart = parts[i].trim();
                                    if (!trimmedPart.isEmpty()) {
                                        // 去掉"类"字，但保留"自动化类"
//                                        trimmedPart = removeClassSuffix(trimmedPart);
                                        uniqueMajors.add(trimmedPart);
                                    }
                                }
                            } else {
                                // 只有一个层级，直接存储
                                String trimmedPart = parts[0].trim();
                                if (!trimmedPart.isEmpty()) {
                                    // 去掉"类"字，但保留"自动化类"
//                                    trimmedPart = removeClassSuffix(trimmedPart);
                                    uniqueMajors.add(trimmedPart);
                                }
                            }
                        }
                    }
                }
            }
        } else {
            // 硕士的专业处理
            List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(openid);
            if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                for (UserMajorRgpp majorRgpp : userMajorRgppList) { //多个专业
                    String majorName = majorRgpp.getMajorName();
                    if (majorName != null && !majorName.trim().isEmpty()) {
                        // 检查是否包含硕士的一级学科
                        if (containsGraduateDiscipline(majorName)) {
                            // 包含一级学科，需要拆分存储
                            String[] parts = majorName.split("-");
                            for (String part : parts) {
                                String trimmedPart = part.trim();
                                if (!trimmedPart.isEmpty()) {
                                    // 去掉"类"字，但保留"自动化类"
//                                    trimmedPart = removeClassSuffix(trimmedPart);
                                    uniqueMajors.add(trimmedPart);
                                }
                            }
                        } else {
                            // 不包含一级学科，只存储二级及以下
                            String[] parts = majorName.split("-");
                            if (parts.length > 1) {
                                // 有多个层级，去掉第一个（一级学科）
                                for (int i = 1; i < parts.length; i++) {
                                    String trimmedPart = parts[i].trim();
                                    if (!trimmedPart.isEmpty()) {
                                        // 去掉"类"字，但保留"自动化类"
//                                        trimmedPart = removeClassSuffix(trimmedPart);
                                        uniqueMajors.add(trimmedPart);
                                    }
                                }
                            } else {
                                // 只有一个层级，直接存储
                                String trimmedPart = parts[0].trim();
                                if (!trimmedPart.isEmpty()) {
                                    // 去掉"类"字，但保留"自动化类"
//                                    trimmedPart = removeClassSuffix(trimmedPart);
                                    uniqueMajors.add(trimmedPart);
                                }
                            }
                        }
                    }
                }
            }
        }

        // 去重后转换为List
        List<String> newMajors = new ArrayList<>(uniqueMajors);


        String graduateTime = userinfo.getGraduateTime();
        String currentYear = String.valueOf(LocalDate.now().getYear());  // 获取当前年份
        int month = LocalDate.now().getMonthValue();  // 获取当前年月份
        String graduateYear = graduateTime.split("-")[0];
        String background = userinfo.getBackground();
        List<String> backgroundList = getBacjground(background);//学历
        //根据每个人的个人信息，获取进行推送数据
        // 判断年份是否相同
        List<Long> jobIds = new ArrayList<>();
        // 获取用户需求信息
        List<String> areaChList = selectOpenidAreaCh(dto, openid);
        List<String> diQu = removeCitySuffix(areaChList);//去掉市的地区

        Job job = new Job();
        if (Objects.equals(dto.getDayTian(), "1")) {
            job.setApplyInstruction("1");
        } else {
            job.setApplyInstruction("0");
        }


        System.out.println(new Date() + "，抵达判断");
        //根据条件获取返回后的 jobIds
        if (month < 7) {
            // 7月前
            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                job.setNatureCn("校招");
                jobIds = getXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear)) {
                job.setNatureCn("实习");
                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
            } else {
                job.setNatureCn("社招");
                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
            }
        } else {
            // 7月及以后
            if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
                job.setNatureCn("社招");
                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
            } else if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear) + 1) {
                job.setNatureCn("校招");
                jobIds = getQYHXZIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
            } else if (Integer.parseInt(graduateYear) > Integer.parseInt(currentYear) + 1) {
                job.setNatureCn("实习");
                jobIds = getIds(userinfo, jobIds, job, backgroundList, newMajors, diQu, graduateYear);
            } else {
                job.setNatureCn("社招");
                String newGraduateYear = getNewGraduateYear(graduateYear) + "届";
                jobIds = jobMapper.selectByIdEs(job, backgroundList, newMajors, diQu, graduateYear, newGraduateYear);
            }
        }

        System.out.println(new Date() + "，获取第一次结果时间");
        //如果没有数据 构建空返回
        if (jobIds.size() <= 0) {
            PageResult pageResult = new PageResult(voList, 0, dto.getPageNum(), dto.getPageSize(), "ok", 200);
            return pageResult;
        }
        // 计算分页参数  （分页查询）
        int pageNumA = dto.getPageNum() == null ? 1 : dto.getPageNum(); // 默认第1页
        int pageSizeB = dto.getPageSize() == null ? 10 : dto.getPageSize(); // 默认每页10条
        int offset = (pageNumA - 1) * pageSizeB;
        dto.setPageNum(pageNumA);
        dto.setPageSize(pageSize);
        dto.setOffset(offset);
        dto.setJobIds(jobIds);

        if (dto.getWhetherMajor() != null) {
            List<String> majList = new ArrayList<>();
            if (Objects.equals(dto.getWhetherMajor(), "本专业")) {
                // 重新获取专业数据
                List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(openid);
                if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
                    Set<String> tempSet = new HashSet<>(); // 用于去重
                    for (UserMajorRgpp item : userMajorRgppList) {
                        String major = item.getMajorName().trim();
                        if (major.contains("-")) {
                            // 分割并跳过第一个大类
                            String[] parts = major.split("-");
                            // 从第二个部分开始处理
                            for (int i = 1; i < parts.length; i++) {
                                String part = parts[i].trim();
                                tempSet.add(part);
                            }
                        } else {
                            // 没有"-"的直接添加
                            tempSet.add(major);
                        }
                    }
                    majList.addAll(tempSet);
                }
            } else {
                majList.add("专业不限");
            }
            dto.setMajList(majList);
        }

        // 确保 dto 和 dto.getAdders() 都不为 null
        List<String> newAdders = new ArrayList<>();
        if (dto != null && dto.getAdders() != null && !dto.getAdders().isEmpty()) {
            for (String addr : dto.getAdders()) {
                // 判断 addr 是否包含 "市"
                if (addr.contains("市")) {
                    // 去掉 "市" 并添加到新集合
                    addr = addr.replace("市", "");
                }
                newAdders.add(addr);  // 添加处理后的地址
            }
            dto.setAdders(newAdders);
        }
        String enterpriseStatus = userinfo.getEnterpriseStatus();//是否推送民企
        dto.setEnterpriseStatus(enterpriseStatus);
        String practiceStatus = userinfo.getPracticeStatus();//是否推送实习
        dto.setPracticeStatus(practiceStatus);
        //是否匹配党员
        String politicsStatus;
        String politics = userinfo.getPolitics();
        if (Objects.equals(politics, "其他") || Objects.equals(politics, "共青团员")) {
            politicsStatus = "1";
        } else {
            politicsStatus = "0";
        }
        dto.setPoliticsStatus(politicsStatus);
        //是否只推送不限专业
        dto.setUnlimitedMajor(userinfo.getUnlimitedMajor());

        if (dto.getSsqylx() != null && !dto.getSsqylx().trim().isEmpty()) {
            dto.setNaturecnConList(splitToList(dto.getSsqylx()));
        }
        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
            dto.setNaturecnList(splitToList(dto.getSsgwlx()));
        }
        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
            dto.setEducationcnList(splitToList(dto.getSsxllx()));
        }
        if (dto.getSsdizhi() != null && !dto.getSsdizhi().trim().isEmpty()) {
            dto.setAdders(splitToList(dto.getSsdizhi()));
        }
        List<Job> jobIdList = jobMapper.findByCom(dto);

        // 获取总记录数
        Long total = jobMapper.getTotalCount();
//        Long total = Long.valueOf(String.valueOf(jobIds.size()));
        if (jobIdList != null && !jobIdList.isEmpty()) {
            for (Job jobs : jobIdList) {
                JobVO vo = new JobVO();
                BeanUtils.copyProperties(jobs, vo);

                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }

                List<Company> company = companyMapper.findByCompanyIdById(jobs.getCompanyId());
                String districtList = jobs.getDistrictList();
                // 创建 Gson 对象
                Gson gson = new Gson();
                if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
                    String areaChListA = getAreaCnList(districtList);
                    vo.setAreaCn(areaChListA);

                }
                if (company != null && !company.isEmpty()) {
                    vo.setIndustryCn(company.get(0).getIndustryCn());
                    vo.setComId(company.get(0).getCompanyId());
                    vo.setName(company.get(0).getName());
                    vo.setComNatureCn(company.get(0).getNatureCn());
                }
                String startTime = formatDate(vo.getStartTime());
                String endTime = formatDate(vo.getEndTime());
                vo.setStartTime(startTime);
                vo.setEndTime(endTime);
                voList.add(vo);
            }
        }
        System.out.println(new Date() + "，获取完整结果返回时间");
        // 构建分页对象
        PageResult pageResult = new PageResult(voList, total, dto.getPageNum(), dto.getPageSize(), "ok", 200);
        return pageResult;
    }

    public static String formatDate(String inputDate) {
        if (inputDate == null || inputDate.trim().isEmpty() || inputDate.equals("0")) {
            return "";
        }
        // 定义输入格式（"yyyy-MM-dd HH:mm:ss"）
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 定义输出格式（"M月d日"）
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy年MM月dd日");
        try {
            // 解析输入的日期字符串
            Date date = inputFormat.parse(inputDate);
            // 返回格式化后的日期字符串
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;  // 返回null表示解析失败
        }
    }


    public static List<String> splitToList(String str) {
        if (str == null || str.trim().isEmpty()) {
            return new ArrayList<>();
        }
        // 支持逗号、中文逗号分隔
        return Arrays.stream(str.split("[,，]"))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
    }


    /**
     * 截取前两位
     *
     * @param graduateYear
     * @return
     */
    private String getNewGraduateYear(String graduateYear) {
        if (graduateYear == null || !graduateYear.matches("\\d+")) {
            return null;
        }
        // 取最后两位（长度不足时直接返回整个字符串）
        int startIndex = Math.max(0, graduateYear.length() - 2);
        return graduateYear.substring(startIndex);
    }

    //封装方法
    @NotNull
    private static PageResult getPageResult(List<JobVO> voList) {
        // 构建分页对象
        PageResult pageResult = new PageResult();
        pageResult.setRows(voList);
        pageResult.setTotal(0); // 总记录数
        pageResult.setMsg("ok");
        pageResult.setCode(200);
        return pageResult;
    }

    // 提取城市名称的方法，去掉"市"字
    private static String extractCity(String areaCn) {
        if (areaCn.endsWith("市")) {
            return areaCn.substring(0, areaCn.length() - 1);  // 去掉"市"字
        }
        return areaCn;  // 如果没有"市"字，直接返回
    }
//
//    //处理专业跟地区 2025-0401
//    private static void majorsAndAdders(String major, List<String> newMajors) {
//
//
//        if (major.contains("-")) {
//            String[] parts = major.split("-"); // 使用 "-" 分隔符将字符串拆分成数组
//            for (String part : parts) {
//                newMajors.add(part.trim()); // 去除每个部分的前后空格，并添加到列表中
//            }
//        } else {
//            newMajors.add(major.trim()); // 如果没有 "-", 将整个字符串添加到列表中
//        }
//    }
//
//    public List<String> getCityList(String searchLocation) {
//        // 判断 searchLocation 是否为 null 或空，避免 NullPointerException
//        if (searchLocation == null || searchLocation.trim().isEmpty()) {
//            return new ArrayList<>(); // 返回空列表
//        }
//
//        // 按逗号分割字符串并去掉"市"
//        String[] cities = searchLocation.split(",");
//
//        List<String> newAddrs = new ArrayList<>();
//        for (String city : cities) {
//            // 去除城市名称中的 "市" 字符，并去除前后空格
//            String cityWithoutShi = city.replace("市", "").trim();
//            newAddrs.add(cityWithoutShi);
//        }
//
//        return newAddrs;
//    }

    /**
     * 返回过滤后的ids
     *
     * @param userinfo
     * @param jobIds
     * @param job
     * @param backgroundList
     * @return
     */
    private List<Long> getIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }

            jobIds = jobMapper.selectByIdBs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);


        } else {
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            //不满足英语4级

            jobIds = jobMapper.selectByIdBs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);
//            if (jobIds.size()>0){
//                List<Job> jobList = jobMapper.selectByJobIds(jobIds);
//
//                Integer userAge = Objects.equals(userinfo.getVeteranStatus(), "是")
//                        ? Integer.parseInt(userinfo.getAge()) + 2
//                        : Integer.parseInt(userinfo.getAge());
//
//
//                jobIds = jobList.stream()
//                        .filter(j -> {
//                            if (j.getContents() != null && j.getContents().toLowerCase().contains("英语四级")) {
//                                return false;  // 过滤掉包含 "英语四级" 的 Job
//                            }
//                            String ageRequirement = extractAgeRequirement(j.getContents());
//                            if (ageRequirement != null) {
//                                try {
//                                    int ageLimit = Integer.parseInt(ageRequirement);
//                                    return userAge <= ageLimit;
//                                } catch (NumberFormatException e) {
//                                    return false;
//                                }
//                            }
//                            // 如果没有年龄要求，则默认符合条件
//                            return true;
//                        })
//                        .map(Job::getId)
//                        .collect(Collectors.toList());
//            }

        }
        return jobIds;
    }

    private List<Long> getXZIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            jobIds = jobMapper.selectByIdCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);

        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            //不满足英语4级
            jobIds = jobMapper.selectByIdCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);
//
//            if (jobIds.size()>0){
//                List<Job> jobList = jobMapper.selectByJobIds(jobIds);
//                Integer userAge = Objects.equals(userinfo.getVeteranStatus(), "是")
//                        ? Integer.parseInt(userinfo.getAge()) + 2
//                        : Integer.parseInt(userinfo.getAge());
//
//                jobIds = jobList.stream()
//                        .filter(j -> {
//                            if (j.getContents() != null && j.getContents().toLowerCase().contains("英语四级")) {
//                                return false;  // 过滤掉包含 "英语四级" 的 Job
//                            }
//                            String ageRequirement = extractAgeRequirement(j.getContents());
//                            if (ageRequirement != null) {
//                                try {
//                                    int ageLimit = Integer.parseInt(ageRequirement);
//                                    return userAge <= ageLimit;
//                                } catch (NumberFormatException e) {
//                                    return false;
//                                }
//                            }
//                            // 如果没有年龄要求，则默认符合条件
//                            return true;
//                        })
//                        .map(Job::getId)
//                        .collect(Collectors.toList());
//            }

        }
        return jobIds;
    }

    //7月后
    private List<Long> getQYHXZIds(WechatUserinfo userinfo, List<Long> jobIds, Job job, List<String> backgroundList, List<String> newMajors, List<String> areaChList, String graduateYear) {

        //判断是不是海外，是
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            jobIds = jobMapper.selectByIdCCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);

        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            //不满足英语4级
            jobIds = jobMapper.selectByIdCCs(job, backgroundList, newMajors, areaChList, graduateYear, englishSix, englishFour);
//            if (jobIds.size()>0){
//                List<Job> jobList = jobMapper.selectByJobIds(jobIds);
//
//                Integer userAge = Objects.equals(userinfo.getVeteranStatus(), "是")
//                        ? Integer.parseInt(userinfo.getAge()) + 2
//                        : Integer.parseInt(userinfo.getAge());
//
//                jobIds = jobList.stream()
//                        .filter(j -> {
//                            if (j.getContents() != null && j.getContents().toLowerCase().contains("英语四级")) {
//                                return false;  // 过滤掉包含 "英语四级" 的 Job
//                            }
//                            String ageRequirement = extractAgeRequirement(j.getContents());
//                            if (ageRequirement != null) {
//                                try {
//                                    int ageLimit = Integer.parseInt(ageRequirement);
//                                    return userAge <= ageLimit;
//                                } catch (NumberFormatException e) {
//                                    return false;
//                                }
//                            }
//                            // 如果没有年龄要求，则默认符合条件
//                            return true;
//                        })
//                        .map(Job::getId)
//                        .collect(Collectors.toList());
//            }

        }
        return jobIds;
    }

    public List<String> getAreaChList(String searchLocation, String nativePlace, String graduateCity) {
        // 使用LinkedHashSet去重并保持顺序
        Set<String> areaSet = new LinkedHashSet<>();

        // 将用户选择的意向地点分别加入集合
        for (String loc : searchLocation.split(",")) {
            String ssss = extractCity(loc.trim());
            areaSet.add(ssss);
        }
        // 提取户籍地信息 (假设格式为 省市格式)
        // 使用正则或简单的字符串拆分来提取
        String[] parts = nativePlace.split("[,，]");  // 使用正则匹配英文或中文逗号
        if (parts.length > 1) {
            // 将市级信息加入 Set 中
            areaSet.add(parts[1].trim());  // 使用 trim() 去除可能的空格
        }


        // 新一线城市
        List<String> cyx = new ArrayList<>(Arrays.asList("北京", "上海", "广州", "深圳", "杭州"));
//        List<String> xyx = new ArrayList<>(Arrays.asList("成都", "重庆", "杭州", "武汉",
//                "苏州", "西安", "南京", "长沙",
//                "天津", "郑州", "东莞", "青岛",
//                "昆明", "宁波", "合肥", "全国"));

        areaSet.addAll(cyx);
//        areaSet.addAll(xyx);

//        // 将用户选择的地点分别加入集合
//        for (String loc : nativePlace.split(",")) {
//            areaSet.add(loc.trim());
//        }
//        for (String loc : graduateCity.split(",")) {
//            areaSet.add(loc.trim());
//        }

        // 将Set转换为List并返回

        return new ArrayList<>(areaSet);
    }


    /**
     * 从 contents 中提取年龄要求（如 "40周岁以下" 中的 40）
     *
     * @param contents 岗位要求内容
     * @return 年龄要求数字（如 "40"），如果没有年龄要求则返回 null
     */
    private static String extractAgeRequirement(String contents) {
        // 正则表达式匹配放宽条件（如 "放宽至40岁以下"）
        Pattern relaxedPattern = Pattern.compile("放宽至(\\d+)岁以下");
        Matcher relaxedMatcher = relaxedPattern.matcher(contents);
        if (relaxedMatcher.find()) {
            return relaxedMatcher.group(1); // 返回放宽条件的年龄
        }

        // 正则表达式匹配原始年龄要求（如 "35周岁以下"）
        Pattern originalPattern = Pattern.compile("(?:年龄)?(\\d+)\\s*周岁以下");
        Matcher originalMatcher = originalPattern.matcher(contents);
        if (originalMatcher.find()) {
            return originalMatcher.group(1); // 返回原始年龄要求
        }

        return null; // 没有匹配到年龄要求
    }

    private List<String> getBacjground(String background) {

        List<String> backgroundList = new ArrayList<>();  //学历
        if (Objects.equals(background, "大专")) {
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else if (Objects.equals(background, "硕士")) {
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
        } else if (Objects.equals(background, "博士")) {
            backgroundList.add("博士");
            backgroundList.add("硕士");
            backgroundList.add("硕士及以上");
            backgroundList.add("博士及以上");
        } else if (Objects.equals(background, "本科")) {
            backgroundList.add("本科");
            backgroundList.add("本科及以上");
            backgroundList.add("大专");
            backgroundList.add("专科及以上");
        } else {
            backgroundList.add("大专");
            backgroundList.add("中专");
            backgroundList.add("中技");
            backgroundList.add("初中");
            backgroundList.add("高中");
            backgroundList.add("初中及以下");
        }
        return backgroundList;
    }

    // 处理VO数据封装
    private List<JobVO> jobVoToList(List<Job> jobList) throws JsonProcessingException, ParseException {
        List<JobVO> voList = new ArrayList<>();
        if (jobList.size() > 0 && !jobList.isEmpty()) {
            for (Job job : jobList) {
                JobVO vo = new JobVO();
                BeanUtils.copyProperties(job, vo);
                if (Objects.equals(vo.getNatureCn(), null)) {
                    vo.setNatureCn("未知");
                }

                if (Objects.equals(job.getEndTime(), "0") || Objects.equals(job.getEndTime(), "null")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String startTime = vo.getStartTime();
                    if (!Objects.equals(startTime, "0")) {
                        Date startDate = sdf.parse(startTime);
                        // 使用 Calendar 类来加上 3 个月
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(startDate);
                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
                        // 将新的时间格式化为字符串
                        String newEndTime = sdf.format(calendar.getTime());
                        vo.setEndTime(newEndTime);
                    }

                } else {
                    String endTime = formatDate(vo.getEndTime());
                    vo.setEndTime(endTime);
                }
                if (!Objects.equals(vo.getStartTime(), "0")) {
                    String startTime = formatDate(vo.getStartTime());
                    vo.setStartTime(startTime);
                }
                String crawlingPlatform = job.getCrawlingPlatform();
                if (Objects.equals(crawlingPlatform, "") || Objects.equals(crawlingPlatform, null)) {
                    vo.setWebsite("www.iguopin.com/job/detail?id=" + job.getJobId());
                } else if (Objects.equals(crawlingPlatform, "菜鸟")) {
                    vo.setWebsite(vo.getSource());
                } else {
                    vo.setWebsite("www.ncss.cn/student/jobs/" + job.getJobId() + "/detail.html");
                }
                String districtList = job.getDistrictList();
                String areaChList = getAreaCnList(districtList);
                vo.setAddrsss(areaChList);//获取地区
//                String companyInfo = job.getCompanyInfo();
//                CompanyVO companyInfoVO = parseCompanyInfo(companyInfo);
                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }
                List<Company> companyList = companyMapper.findByCompanyId(vo.getCompanyId());
                if (companyList != null && !companyList.isEmpty()) {
                    vo.setName(companyList.get(0).getName());
                    vo.setIndustryCn(companyList.get(0).getIndustry());
                    vo.setGyqy(companyList.get(0).getNature());

                }
                vo.setCompanyList(companyList);
                voList.add(vo);
            }
        }
        return voList;
    }


    private List<JobVO> jobVoToAAAList(List<JobVO> jobList) throws JsonProcessingException, ParseException {
        List<JobVO> voList = new ArrayList<>();
        if (jobList.size() > 0 && !jobList.isEmpty()) {
            for (JobVO jobVO : jobList) {
                JobVO vo = new JobVO();
                BeanUtils.copyProperties(jobVO, vo);
                if (Objects.equals(vo.getNatureCn(), null)) {
                    vo.setNatureCn("未知");
                }

//                if (Objects.equals(jobVO.getEndTime(), "0") || Objects.equals(jobVO.getEndTime(), "null")) {
//                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    String startTime = vo.getStartTime();
//                    if (!Objects.equals(startTime, "0")) {
//                        Date startDate = sdf.parse(startTime);
//                        // 使用 Calendar 类来加上 3 个月
//                        Calendar calendar = Calendar.getInstance();
//                        calendar.setTime(startDate);
//                        calendar.add(Calendar.MONTH, 3); // 加 3 个月
//                        // 将新的时间格式化为字符串
//                        String newEndTime = sdf.format(calendar.getTime());
//                        vo.setEndTime(newEndTime);
//                    }
//
//                } else {
//                    String endTime = formatDate(vo.getEndTime());
//                    vo.setEndTime(endTime);
//                }
                String startTime = formatDate(vo.getUpdateTime());
                vo.setStartTime(startTime);

                String crawlingPlatform = jobVO.getCrawlingPlatform();
                if (Objects.equals(crawlingPlatform, "") || Objects.equals(crawlingPlatform, null)) {
                    vo.setWebsite("www.iguopin.com/job/detail?id=" + jobVO.getJobId());
                } else if (Objects.equals(crawlingPlatform, "菜鸟")) {
                    vo.setWebsite(vo.getSource());
                } else {
                    vo.setWebsite("www.ncss.cn/student/jobs/" + jobVO.getJobId() + "/detail.html");
                }
                String districtList = jobVO.getDistrictList();
                String areaChList = getAreaCnList(districtList);
                vo.setAddrsss(areaChList);//获取地区
//                String companyInfo = job.getCompanyInfo();
//                CompanyVO companyInfoVO = parseCompanyInfo(companyInfo);
                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }
                List<Company> companyList = companyMapper.findByCompanyId(vo.getCompanyId());
                if (companyList != null && !companyList.isEmpty()) {
                    vo.setName(companyList.get(0).getName());
                    vo.setIndustryCn(companyList.get(0).getIndustry());
                    vo.setGyqy(companyList.get(0).getNature());

                }
                vo.setCompanyList(companyList);
                voList.add(vo);
            }
        }
        return voList;
    }

//    public CompanyVO parseCompanyInfo(String companyInfo) throws JsonProcessingException {
//        // 创建 ObjectMapper 实例（建议作为类成员变量复用）
//        ObjectMapper objectMapper = new ObjectMapper();
//
//        try {
//            // 1. 将单引号替换为双引号
//            companyInfo = companyInfo.replace("'", "\"");
//
//            // 2. 解析JSON字符串为Map
//            Map<String, Object> companyMap = objectMapper.readValue(
//                    companyInfo,
//                    new TypeReference<Map<String, Object>>() {
//                    }
//            );
//
//            // 3. 创建并填充VO对象
//            CompanyVO companyVO = new CompanyVO();
//
//            // 4. 安全提取字段（带默认值处理）
//            companyVO.setName(getStringValue(companyMap, "name"));
//            companyVO.setNature(getStringValue(companyMap, "nature"));
//            companyVO.setIndustry(getStringValue(companyMap, "industry"));
//
////            // 5. 处理可能存在的嵌套对象（示例）
////            if (companyMap.containsKey("address")) {
////                Object addressObj = companyMap.get("address");
////                if (addressObj instanceof Map) {
////                    @SuppressWarnings("unchecked")
////                    Map<String, Object> addressMap = (Map<String, Object>) addressObj;
////                    companyVO.setAddress(getStringValue(addressMap, "fullAddress"));
////                }
////            }
//
//            return companyVO;
//
//        } catch (JsonProcessingException e) {
//            log.error("JSON解析失败: {}", companyInfo, e);
//            throw e;
//        } catch (Exception e) {
//            log.error("公司信息转换异常", e);
//            throw new IllegalArgumentException("公司信息格式不正确");
//        }
//    }


    // 安全获取String类型字段的辅助方法
    private String getStringValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value == null) {
            return null;
        }
        return value.toString(); // 自动处理数字等其他类型
    }

    // 安全获取嵌套对象字段的辅助方法（示例）
    private <T> T getNestedValue(Map<String, Object> map, String key, Class<T> clazz) {
        Object value = map.get(key);
        if (value != null && clazz.isInstance(value)) {
            return clazz.cast(value);
        }
        return null;
    }

    // 方法：将多个 area_cn 拼接为一个字符串，用逗号分隔
//    public static String getAreaCnList(String districtListJson) {
//        try {
//            // Create an ObjectMapper instance
//            ObjectMapper objectMapper = new ObjectMapper();
//
//            // Parse the JSON into a JsonNode
//            JsonNode rootNode = objectMapper.readTree(districtListJson.replace("'", "\""));
//
//            // Check if the root is an array
//            if (rootNode.isArray()) {
//                // If it's an array, process it as a list of objects
//                List<Map<String, String>> list = objectMapper.convertValue(rootNode, List.class);
//
//                // Using Java 8 Stream API to map and join area_cn fields
//                String result = list.stream()
//                        .map(item -> (String) item.get("area_cn"))
//                        .collect(Collectors.joining(","));
//
//                return result;
//            } else {
//                // If it's a single object (not an array), process it directly
//                String areaCn = rootNode.path("area_cn").asText();
//                return areaCn != null ? areaCn : "";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "";
//        }
//    }
// 方法：将多个 area_cn 拼接为一个字符串，用逗号分隔
    public static String getAreaCnList(String districtListJson) {
        if (StringUtils.isBlank(districtListJson)) {
            return "";
        }

        String trimmed = districtListJson.trim();

        // 检查是否是JSON格式
        if (isJsonFormat(trimmed)) {
            try {
                // Create an ObjectMapper instance
                ObjectMapper objectMapper = new ObjectMapper();

                // Parse the JSON into a JsonNode
                JsonNode rootNode = objectMapper.readTree(trimmed.replace("'", "\""));

                // Check if the root is an array
                if (rootNode.isArray()) {
                    // If it's an array, process it as a list of objects
                    List<Map<String, String>> list = objectMapper.convertValue(rootNode, List.class);

                    // Using Java 8 Stream API to map and join area_cn fields
                    String result = list.stream()
                            .map(item -> (String) item.get("area_cn"))
                            .filter(Objects::nonNull) // 过滤null值
                            .collect(Collectors.joining(","));

                    return result;
                } else {
                    // If it's a single object (not an array), process it directly
                    String areaCn = rootNode.path("area_cn").asText();
                    return areaCn != null ? areaCn : "";
                }
            } catch (Exception e) {
                // JSON解析失败，回退到字符串处理
                log.warn("JSON解析失败，使用字符串分割: {}", districtListJson, e);
                return parsePlainString(trimmed);
            }
        } else {
            // 非JSON格式，直接返回原字符串或按需处理
            return parsePlainString(trimmed);
        }
    }

    // 判断是否为JSON格式
    private static boolean isJsonFormat(String str) {
        if (str == null || str.trim().isEmpty()) {
            return false;
        }
        String trimmed = str.trim();
        return (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
                (trimmed.startsWith("{") && trimmed.endsWith("}"));
    }

    // 处理普通字符串格式
    private static String parsePlainString(String str) {
        // 如果已经是逗号分隔的字符串，直接返回
        if (str.contains(",")) {
            return str;
        }
        // 如果是单个值，直接返回
        return str;
    }
    public static List<String> removeCitySuffix(List<String> areaChList) {
        // 创建一个新的列表，用来存储去除"市"后的城市名称
        List<String> resultList = new ArrayList<>();

        // 遍历原始列表，去除每个城市名称中的"市"
        for (String area : areaChList) {
            // 去除 "市" 字符串
            String cityWithoutSuffix = area.replace("市", "");
            // 将处理后的城市名称添加到新的列表
            resultList.add(cityWithoutSuffix);
        }

        return resultList;
    }


    private List<String> selectOpenidAreaCh(JobDTO dto, String openid) {
        List<String> areaChList = new ArrayList<>();
        List<UserDemand> demandList = demandMapper.findByOpenid(openid);
        if (demandList != null && !demandList.isEmpty()) {
            UserDemand demand = demandList.get(0); // 获取第一个需求信息
            String searchLocation = demand.getSearchLocation(); // 意向地点
            String nativePlace = demand.getNativePlace(); // 户籍地
            String graduateCity = demand.getGraduateCity(); // 毕业院校城市
            areaChList = getAreaChList(searchLocation, nativePlace, graduateCity);
            dto.setAreaChList(areaChList);
        }
        return areaChList;
    }

    //修改岗位筛选查询
    @Override
    public PageResult<JobVO> selectBycesAAA(JobDTO dto, Integer pageNum, Integer pageSize) {
        List<JobVO> voList = new ArrayList();
        String openid = dto.getOpenid();
        if (!StringUtils.isNotNull(openid)) {
            // 构建分页对象
            return getPageResult(voList);
        }
        WechatUserinfo userinfo = userinfoMapper.findByOpenid(openid);
        if (userinfo == null) {
            // 构建分页对象
            return getPageResult(voList);
        }
        //添加搜索记录------------------------，处理用户的筛选记录存储
        if (!Objects.equals(dto.getZygwqi(), null)) {
            SearchContent searchContent = new SearchContent();
            int count = contentMapper.findByOpenidAndContent(openid, dto.getZygwqi());
            if (count <= 0) {//不存在这个搜索记录,添加
                searchContent.setOpenid(openid);
                searchContent.setContent(dto.getZygwqi());
                contentMapper.insert(searchContent);
            }
        }
        JobCondition jobCondition = new JobCondition();//存储用户自带岗位筛序条件存储
        //对专业的处理
        List<String> newMajors = new ArrayList<>();
        Set<String> majorsSet = new HashSet<>();
        List<UserMajorRgpp> userMajorRgppList = userMajorRgppMapper.findByOpenid(openid);
        if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
            List<String> majorList = userMajorRgppList.stream().map(UserMajorRgpp::getMajorName).collect(Collectors.toList());
            for (String major : majorList) {
                if (major.contains("-")) {
                    String[] parts = major.split("-"); // 使用 "-" 分隔符将字符串拆分成数组
                    for (String part : parts) {
                        majorsSet.add(part.trim()); // 去除每个部分的前后空格，并添加到列表中
                    }
                } else {
                    majorsSet.add(major.trim()); // 如果没有 "-", 将整个字符串添加到列表中
                }
            }


        }
        newMajors.addAll(majorsSet);//去重后添加到 新集合中

        //对学历的处理
        String background = userinfo.getBackground();
        List<String> backgroundList = getBacjground(background);//学历


        //获取用户毕业年限 做岗位筛选
        String graduateTime = userinfo.getGraduateTime();
        String currentYear = String.valueOf(LocalDate.now().getYear());  // 获取当前年份
        int month = LocalDate.now().getMonthValue();  // 获取当前年月份
        String graduateYear = graduateTime.split("-")[0];

        //根据每个人的个人信息，获取进行推送数据
        // 判断年份是否相同

        List<Job> jobIdList = new ArrayList<>();
        // 获取用户需求信息
        if (dto.getSsqylx() != null && !dto.getSsqylx().trim().isEmpty()) {
            jobCondition.setJobNaturecnList(splitToList(dto.getSsqylx()));
        }
//        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
//            dto.setNaturecnList(splitToList(dto.getSsgwlx()));
//        }
        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
            jobCondition.setConditionBackgroundList(splitToList(dto.getSsxllx()));
        } else {
            jobCondition.setConditionBackgroundList(backgroundList);
        }
        if (dto.getSsdizhi() != null && !dto.getSsdizhi().trim().isEmpty()) {
            jobCondition.setConditionBackAreaChList(splitToList(dto.getSsdizhi()));
        } else {
            List<String> areaChList = selectOpenidAreaCh(dto, openid);
            List<String> diQu = removeCitySuffix(areaChList);//去掉市的地区
            jobCondition.setConditionBackAreaChList(diQu);
        }


        String enterpriseStatus = userinfo.getEnterpriseStatus();//是否推送民企
        jobCondition.setEnterpriseStatus(enterpriseStatus);
        String practiceStatus = userinfo.getPracticeStatus();//是否推送实习
        jobCondition.setPracticeStatus(practiceStatus);
        //是否匹配党员
        String politicsStatus;
        String politics = userinfo.getPolitics();
        if (Objects.equals(politics, "其他") || Objects.equals(politics, "共青团员")) {
            politicsStatus = "1";
        } else {
            politicsStatus = "0";
        }
        jobCondition.setPoliticsStatus(politicsStatus);

        if (Objects.equals(dto.getDayTian(), "1")) {
            jobCondition.setTimeBound("1");
        } else {
            jobCondition.setTimeBound("0");
        }


        jobCondition.setConditionMajors(newMajors);

        jobCondition.setConditionCurrentYear(currentYear);
        if (Objects.equals(userinfo.getOverseasStudent(), "是") || Objects.equals(userinfo.getEnglishFour(), "是")) {

            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            jobCondition.setEnglishFour(englishFour);
            jobCondition.setEnglishSix(englishSix);
        } else {
            String englishFour = "0";
            if (Objects.equals(userinfo.getEnglishFour(), "是")) {
                englishFour = "1";
            }
            String englishSix = "0";
            if (Objects.equals(userinfo.getEnglishSix(), "是")) {
                englishSix = "1";
            }
            jobCondition.setEnglishFour(englishFour);
            jobCondition.setEnglishSix(englishSix);

        }
        jobCondition.setConditionNatureCn("校招");


        System.out.println(new Date() + "，抵达判断");
        Page<Job> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        // 根据毕业年份处理查询
        if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear)) {
            // 不查询，返回空分页
        } else if (Integer.parseInt(graduateYear) == Integer.parseInt(currentYear) + 1) {
            // 使用 MyBatis-Plus 分页查询
            page = jobMapper.selectByIdTextCCs(page, jobCondition, dto);
        }

        System.out.println(new Date() + "，结束查询");

        // 转换Job到JobVO（需补充转换逻辑）
        List<JobVO> voListA = convertToJobVOList(page.getRecords());
        // 构建分页结果（自动获取总记录数）
        return new PageResult<>(voListA, page.getTotal(), dto.getPageNum(), dto.getPageSize(), "ok", 200);
//
//
//        if (dto.getWhetherMajor() != null) {
//            List<String> majList = new ArrayList<>();
//            if (Objects.equals(dto.getWhetherMajor(), "本专业")) {
//                if (userMajorRgppList != null && !userMajorRgppList.isEmpty()) {
//                    List<String> majorList = userMajorRgppList.stream().map(UserMajorRgpp::getMajorName).collect(Collectors.toList());
//                    for (String major : majorList) {
//                        if (major.contains("-")) {
//                            String[] parts = major.split("-"); // 使用 "-" 分隔符将字符串拆分成数组
//                            for (String part : parts) {
//                                newMajors.add(part.trim()); // 去除每个部分的前后空格，并添加到列表中
//                            }
//                        } else {
//                            newMajors.add(major.trim()); // 如果没有 "-", 将整个字符串添加到列表中
//                        }
//                    }
//
//
//                }
//            } else {
//                //不限专业
//                majList.add("专业不限");
//            }
//            dto.setMajList(majList);
//        }
//
//        // 确保 dto 和 dto.getAdders() 都不为 null
//        List<String> newAdders = new ArrayList<>();
//        if (dto != null && dto.getAdders() != null && !dto.getAdders().isEmpty()) {
//            for (String addr : dto.getAdders()) {
//                // 判断 addr 是否包含 "市"
//                if (addr.contains("市")) {
//                    // 去掉 "市" 并添加到新集合
//                    addr = addr.replace("市", "");
//                }
//                newAdders.add(addr);  // 添加处理后的地址
//            }
//            dto.setAdders(newAdders);
//        }
//
//        dto.setEnterpriseStatus(enterpriseStatus);
//
//        dto.setPracticeStatus(practiceStatus);
//        //是否匹配党员
//
//
//        dto.setPoliticsStatus(politicsStatus);
//
//        if (dto.getSsqylx() != null && !dto.getSsqylx().trim().isEmpty()) {
//            dto.setNaturecnConList(splitToList(dto.getSsqylx()));
//        }
//        if (dto.getSsgwlx() != null && !dto.getSsgwlx().trim().isEmpty()) {
//            dto.setNaturecnList(splitToList(dto.getSsgwlx()));
//        }
//        if (dto.getSsxllx() != null && !dto.getSsxllx().trim().isEmpty()) {
//            dto.setEducationcnList(splitToList(dto.getSsxllx()));
//        }
//        if (dto.getSsdizhi() != null && !dto.getSsdizhi().trim().isEmpty()) {
//            dto.setAdders(splitToList(dto.getSsdizhi()));
//        }
//        List<Job> jobIdList = jobMapper.findByCom(dto);
//
//        // 获取总记录数
//        Long total = jobMapper.getTotalCount();
////        Long total = Long.valueOf(String.valueOf(jobIds.size()));
//        if (jobIdList != null && !jobIdList.isEmpty()) {
//            for (Job jobs : jobIdList) {
//                JobVO vo = new JobVO();
//                BeanUtils.copyProperties(jobs, vo);
//
//                if (!Objects.equals(vo.getMajorCn(), null)) {
//                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
//                    if (!majorCn.isEmpty()) {
//                        // 按逗号分隔，并过滤掉空字符串
//                        List<String> list = Arrays.stream(majorCn.split(","))
//                                .map(String::trim) // 去除每个元素的前后空格
//                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
//                                .collect(Collectors.toList());
//                        vo.setMajorList(list);
//                    } else {
//                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
//                    }
//                } else {
//                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
//                }
//
//                List<Company> company = companyMapper.findByCompanyIdById(jobs.getCompanyId());
//                String districtList = jobs.getDistrictList();
//                // 创建 Gson 对象
//                Gson gson = new Gson();
//                if (districtList != null) {
//                    // 解析 JSON 字符串
//                    List<Map<String, Object>> districtListData = gson.fromJson(districtList, List.class);
//
//                    // 用来存储所有的 area_cn 字段
//                    StringBuilder areaCnBuilder = new StringBuilder();
//
//                    // 遍历所有数据项，获取每个 area_cn 的值
//                    for (Map<String, Object> district : districtListData) {
//                        Object areaCnObject = district.get("area_cn");
//                        if (areaCnObject instanceof String) {
//                            // 添加到 StringBuilder
//                            if (areaCnBuilder.length() > 0) {
//                                areaCnBuilder.append("、"); // 使用中文逗号连接
//                            }
//                            areaCnBuilder.append(areaCnObject.toString());
//                        }
//                    }
//                    // 获取合并后的 area_cn 字符串
//                    String areaCn = areaCnBuilder.toString();
//                    vo.setAreaCn(areaCn);
//                } else {
//                    // 如果 districtList 为 null，使用 companyList
//                    if (company != null && !company.isEmpty()) {
//                        String areaCn = company.get(0).getAreaCn();
//                        vo.setAreaCn(areaCn);
//                    }
//
//                }
//                if (company != null && !company.isEmpty()) {
//                    vo.setIndustryCn(company.get(0).getIndustryCn());
//                    vo.setComId(company.get(0).getCompanyId());
//                    vo.setName(company.get(0).getName());
//                    vo.setComNatureCn(company.get(0).getNatureCn());
//                }
//                String startTime = formatDate(vo.getStartTime());
//                String endTime = formatDate(vo.getEndTime());
//                vo.setStartTime(startTime);
//                vo.setEndTime(endTime);
//                voList.add(vo);
//            }
//        }
//        System.out.println(new Date() + "，获取完整结果返回时间");
//         构建分页对象
//        PageResult pageResult = new PageResult(voList, total, dto.getPageNum(), dto.getPageSize(), "ok", 200);
//        return pageResult;
//        return null;
    }

    /**
     * 热门岗位近一周央国企数据
     *
     * @param dto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResult<CompanyJobVO> getHotTest(JobDTO dto, Integer pageNum, Integer pageSize) {
        Page<CompanyJobVO> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        page = jobMapper.selectByIdTextHot(page, dto);
//        List<CompanyJobVO> voList = jobMapper.getHot(dto);
        List<CompanyJobVO> records = page.getRecords();
        if (records != null && !records.isEmpty()) {
            for (CompanyJobVO vo : records) {
                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }
                String districtList = vo.getDistrictList();
                Gson gson = new Gson();
                // 解析 JSON 字符串
                String areaCn = null;
                if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
                    String areaChList = getAreaCnList(districtList);
                    vo.setAreaCn(areaChList);

                }
                String startTime = formatDate(vo.getStartTime());
                String endTime = formatDate(vo.getEndTime());
                vo.setStartTime(startTime);
                vo.setEndTime(endTime);
            }
            PageResult pageResult = new PageResult(records, page.getTotal(), dto.getPageNum(), dto.getPageSize(), "ok", 200);
            return pageResult;
        } else {
            PageResult pageResult = new PageResult(records, 0, dto.getPageNum(), dto.getPageSize(), "ok", 200);
            return pageResult;
        }

    }


    // 辅助方法：Job转JobVO（示例）
    private List<JobVO> convertToJobVOList(List<Job> jobList) {
        List<JobVO> result = new ArrayList<>();
//         构建分页结果（自动获取总记录数）
        if (jobList != null && !jobList.isEmpty()) {
            for (Job jobs : jobList) {
                JobVO vo = new JobVO();
                BeanUtils.copyProperties(jobs, vo);

                if (!Objects.equals(vo.getMajorCn(), null)) {
                    String majorCn = vo.getMajorCn().trim(); // 去除前后空格
                    if (!majorCn.isEmpty()) {
                        // 按逗号分隔，并过滤掉空字符串
                        List<String> list = Arrays.stream(majorCn.split(","))
                                .map(String::trim) // 去除每个元素的前后空格
                                .filter(s -> !s.isEmpty()) // 过滤掉空字符串
                                .collect(Collectors.toList());
                        vo.setMajorList(list);
                    } else {
                        vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                    }
                } else {
                    vo.setMajorList(new ArrayList<>()); // 如果 majorCn 是空字符串，返回空列表
                }

                List<Company> company = companyMapper.findByCompanyIdById(jobs.getCompanyId());
                String districtList = jobs.getDistrictList();
                // 创建 Gson 对象
                Gson gson = new Gson();

                // 解析 JSON 字符串
                String areaCn = null;
                if (!Objects.equals(districtList, null) && !Objects.equals(districtList, "")) {
                    String areaChList = getAreaCnList(districtList);
                    vo.setAreaCn(areaChList);

                } else {
                    if (company != null && !company.isEmpty()) {// 如果 districtList 为 null，使用 companyList
                        areaCn = company.get(0).getAreaCn();
                    }
                    vo.setAreaCn(areaCn);
                }
                if (company != null && !company.isEmpty()) {
                    vo.setIndustryCn(company.get(0).getIndustryCn());
                    vo.setComId(company.get(0).getCompanyId());
                    vo.setName(company.get(0).getName());
                    vo.setComNatureCn(company.get(0).getNatureCn());
                }
                String startTime = formatDate(vo.getStartTime());
                String endTime = formatDate(vo.getEndTime());
                vo.setStartTime(startTime);
                vo.setEndTime(endTime);
                result.add(vo);
            }
        }
        System.out.println(new Date() + "，获取完整结果返回时间");
//         构建分页对象

        return result;
    }

    /**
     * 检查专业是否包含本科/大专的一级学科
     * 本科/大专的一级学科：哲学，经济学，教育学，文学，历史学，管理学，艺术学
     */
    private boolean containsUndergraduateDiscipline(String majorName) {
        if (majorName == null) return false;

        String[] undergraduateDisciplines = {
                "哲学", "经济学", "教育学", "文学", "历史学", "管理学", "艺术学"
        };

        for (String discipline : undergraduateDisciplines) {
            if (majorName.contains(discipline)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查专业是否包含硕士的一级学科
     * 硕士的一级学科：哲学，经济学，教育学，文学，历史学，管理学，军事学，艺术学
     */
    private boolean containsGraduateDiscipline(String majorName) {
        if (majorName == null) return false;

        String[] graduateDisciplines = {
                "哲学", "经济学", "教育学", "文学", "历史学", "管理学", "军事学", "艺术学"
        };

        for (String discipline : graduateDisciplines) {
            if (majorName.contains(discipline)) {
                return true;
            }
        }
        return false;
    }

    private String removeClassSuffix(String majorName) {
        // 去掉"类"字，但保留"自动化类"
        if ("自动化类".equals(majorName)) {
            return majorName; // 保留"自动化类"
        }
        return majorName.replace("类", "");
    }
}
